<?php

namespace App\Admin\Repositories;

use App\Models\ProjectUser as Model;
use Dcat\Admin\Repositories\EloquentRepository;
use App\Models\AdminUser;
use App\Models\Project;
use App\Models\ProjectUser as ModelsProjectUser;
use App\Models\User;
use Carbon\Carbon;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;

class ProjectUser extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;


    public function get(Grid\Model $model)
    {
        $dataWhere = null;
        $currLoginUser = Admin::user();
        $params = request()->input();

        $builder = DB::table('project_user as pu');


        $dataWhere = function ($query) use ($currLoginUser, $params) {
            if ($currLoginUser->isAdministrator()) {
                $query->where('pu.project_id', $params['project_id']);
            }
            // 如果是项目总负责人
            if ($currLoginUser->isRole('project-manager')) {
                // 根据用户的公司id查询公司下所有的项目id
                // $project_id = Project::where('company_id', $currLoginUser->company_id)->pluck('id');

                $query->where('pu.project_id', $params['project_id']);
            }

            // 如果是区域经理  查看本区域下代理人创建的协议
            if ($currLoginUser->isRole('regional-supervisor')) {
                // 查询代理人, 'admin_id' => $currLoginUser->id
                $agent = AdminUser::where(['company_id' => $currLoginUser->company_id, 'region' => $currLoginUser->region, 'status' => 1])->pluck('id');

                $query->whereIn('u.agent', $agent);
            }
            // 如果是代理人的话查看自己创建的用户
            if ($currLoginUser->isRole('agent')) {
                $query->where('u.agent', $currLoginUser->id)->where('u.company_id', $currLoginUser->company_id);;
            }
        };

        // 限制条数
        if (isset($params['per_page']) && !empty($params['per_page'])) {
            $per_page = $params['per_page'];
        } else {
            $per_page = 20;
        }

        $builder->select([
            'pu.*',
            'p.id as p.project_id', 'p.company_id', 'p.tpl_id', 'p.project_name', 'p.status',
            'u.id as u.user_id', 'u.company_id', 'u.realname', 'u.phone', 'u.id_number', 'u.status as user_status', 'u.unit', 'u.unit_level', 'u.department', 'u.title', 'u.agent', 'u.agent_code'
        ])
            ->join('project as p', 'pu.project_id', '=', 'p.id')
            ->join('users as u', 'pu.user_id', '=', 'u.id');

        return $builder->where($dataWhere)
            ->where(function (Builder $query) use ($params) {
                if (!empty($params['realname'])) {
                    $query->where('u.realname', $params['realname']);
                }
                if (!empty($params['phone'])) {
                    $query->where('u.phone', $params['phone']);
                }
                if (!empty($params['unit'])) {
                    $query->where('u.unit', 'like', "%" . $params['unit'] . "%");
                }

                if (!empty($params['title'])) {
                    $query->where('u.title', $params['title']);
                }
                if (!empty($params['unit_level'])) {
                    $query->where('u.unit_level', $params['unit_level']);
                }
            })
            ->where('pu.deleted_at', null)
            ->orderBy('pu.id', 'desc')
            ->paginate($per_page);
    }


    public function store(Form $form)
    {
        // 获取待新增的数据
        $attributes = $form->updates();
        $project = Project::find($attributes['project_id']);
        // if (!empty($project->project_end_time)) {
        // if (Carbon::now() > $project->project_end_time) {
        if (!empty($project->submit_info_end_time)) {
            if (Carbon::now() > $project->submit_info_end_time) {
                return $form->response()->error('项目资料收集已结束');
            }
        }

        $number_of_attendees = $project->number_of_attendees ?? 0;
        if ($number_of_attendees > 0) {
            $projectUserCount = ModelsProjectUser::where('project_id', $attributes['project_id'])->count();
            if ($projectUserCount >= $number_of_attendees) {
                return $form->response()->error('参会人数已到最大值');
            }
        }

        // 执行你的新增逻辑
        $user = [
            'company_id' => $attributes['company_id'],
            'realname' => $attributes['realname'],
            'phone' => $attributes['phone'],
            'id_number' => $attributes['id_number'],
            'ip' => request()->ip(),
            'status' => 1,
            'province_id' => $attributes['province_id'],
            'city_id' => $attributes['city_id'],
            'district_id' => $attributes['district_id'],
            'unit' => $attributes['unit'],
            'unit_level' => $attributes['unit_level'],
            'department' => $attributes['department'],
            'title' => $attributes['title'],
            'bank_number' => $attributes['bank_number'],
            'bank_opening' => $attributes['bank_opening'],
            'bank_account_open_local' => $attributes['bank_account_open_local'],
            'agent' => $attributes['agent'],
            'agent_code' => $attributes['agent_code'],
            'certificate1' => $attributes['certificate1'],
            'certificate2' => $attributes['certificate2'],
        ];

        try {

            $userModel = User::create($user);
            // 判断参会人数 大于0的时候统计
            $ProjectUserModel = ModelsProjectUser::create([
                'project_id' => $attributes['project_id'],
                'user_id' => $userModel->id,
            ]);
            if ($userModel && $ProjectUserModel) {
                return true;
            }
        } catch (\Exception $e) {
            return true;
        }
    }
}
